<template>
    <div class="app-container">
        <el-form :model="postForm" :rules="rules" ref="postForm" label-width="150px" style="width: 80%;">
            <el-form-item label="课程URL" v-if="postForm.id > 0">
                <input name="forCopyBtn" id="courseUrlInput" :value="courseUrl" type="hidden">
                <el-input disabled="disabled" :value="courseUrl" >
                    <el-button slot="append" icon="document" id="copyBtn" data-clipboard-target="#courseUrlInput">拷贝</el-button>
                </el-input>
            </el-form-item>
            <el-form-item label="课程名称" prop="name">
                <el-input v-model="postForm.name"></el-input>
            </el-form-item>
            <el-form-item label="课程简介" prop="briefDesc">
                <el-input type="text" v-model="postForm.briefDesc"></el-input>
            </el-form-item>
            <el-form-item label="课程介绍" prop="detailDesc">
                <el-input type="textarea" v-model="postForm.detailDesc"></el-input>
            </el-form-item>
            <el-form-item label="课程缩略图" prop="thumbImgUrl">
                <el-upload
                        :action="actionUrl"
                        :drag="true"
                        :multiple="false"
                        :with-credentials="true"
                        :show-file-list="true"
                        accept="image/*"
                        :on-success="handleThumbSuccess"
                        :before-upload="beforeUpload"
                        >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，建议尺寸148px*148px 宽:高 = 1:1</div>
                </el-upload>
                <img :src="postForm.thumbImgUrl" style="width:54px; height: 54px;">
            </el-form-item>
            <el-form-item label="课程图片" prop="imgUrl">
                <el-upload
                        :action="actionUrl"
                        :drag="true"
                        :multiple="false"
                        :with-credentials="true"
                        :show-file-list="true"
                        accept="image/*"
                        :on-success="handleSuccess"
                        :before-upload="beforeUpload"
                >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，建议尺寸750px*525px 宽:高 = 10:7</div>
                </el-upload>
                <img :src="postForm.imgUrl" style="width:200px; height: 140px;">
            </el-form-item>
            <el-form-item label="作者" prop="authorId">
                <el-select v-model="postForm.authorId" placeholder="请选择">
                    <el-option
                            v-for="item in authorOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="来源" prop="sourceId">
                <el-select v-model="postForm.sourceId" placeholder="请选择">
                    <el-option
                            v-for="item in sourceOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="原价(单位：分)" prop="orgPrice">
                <el-input type="text" v-model.number="postForm.orgPrice"></el-input>
            </el-form-item>
            <el-form-item label="折后价(单位：分)" prop="discPrice">
                <el-input type="text" v-model.number="postForm.discPrice"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="cateIdList">
                <el-checkbox-group
                        v-model="postForm.cateIdList">
                    <el-checkbox v-for="category in categoryOptions" :label="category.id" :key="category.id">{{category.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="序号" prop="serial">
                <el-input type="text" v-model.number="postForm.serial"></el-input>
            </el-form-item>
            <el-form-item label="购买须知" prop="buyNote">
                <el-input type="textarea" v-model="postForm.buyNote"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button v-loading="loading" type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

    import { getDetail, add, update, getCategorys } from '@/api/course';
    import { getList as _getAuthorList } from '@/api/author';
    import { getList as _getSourceList } from '@/api/source';
    import { getList as _getCategoryList } from '@/api/category';
    import * as Clipboard from 'clipboard';


    var clipboard = null;

    export default {
        data() {
            return {
                loading: false,
                actionUrl: process.env.BASE_API + '/common/upload/img',
                courseUrl: '',
                authorOptions: [],
                sourceOptions: [],
                categoryOptions: [],
                postForm: {
                    id: '',
                    name: '',
                    briefDesc: '',
                    detailDesc: '',
                    thumbImgUrl: '',
                    imgUrl: '',
                    authorId: '',
                    sourceId: '',
                    orgPrice: 0,
                    status: 0,
                    discPrice: 0,
                    cateIdList: [],
                    serial: 1,
                    buyNote: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入课程名称', trigger: 'blur' },
                        { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
                    ],
                    briefDesc: [
                        { required: true, message: '请输入课程简介', trigger: 'blur' },
                        { min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }
                    ],
                    detailDesc: [
                        { required: true, message: '请输入课程描述', trigger: 'blur' }
                    ],
                    imgUrl: [
                        { required: true, message: '请输入上传课程图片', trigger: 'blur' }
                    ],
                    thumbImgUrl: [
                        { required: true, message: '请输入上传课程缩略图', trigger: 'blur' }
                    ],
                    authorId: [
                        { type: 'integer', required: true, message: '请选择作者', trigger: 'change' }
                    ],
                    sourceId: [
                        { type: 'integer', required: true, message: '请选择来源', trigger: 'change' }
                    ],
                    cateIdList: [
                        { type: 'array', required: true, message: '请至少选择一个分类', trigger: 'change' }
                    ],
                    orgPrice: [
                        { type: 'integer', required: true, message: '请输入原价（整数）, 输入0表示不显示原价', min: 0, trigger: 'blur' }
                    ],
                    discPrice: [
                        { type: 'integer', required: true, message: '请输入折后价（正整数）', min: 1, trigger: 'blur' }
                    ],
                    serial: [
                        { type: 'integer', required: true, message: '请输入序号（正整数）', min: 1, trigger: 'blur' }
                    ],
                    buyNote: [
                        { required: true, message: '请输入购买须知', trigger: 'blur' }
                    ]
                },
                isUpdate: false
            }
        },
        created() {
            const reg = /\/update\/(\d*)$/
            if (reg.test(this.$route.path)) {
                this.isUpdate = true;
                const ID = RegExp.$1;
                this.fetchData(ID);
                this.getCourseCategory(ID);
            }
            this.getSourceList();
            this.getAuthorList();
            this.getCategoryList();
        },
        mounted() {
//            if (clipboard == null) {
//                clipboard = new Clipboard('#copyBtn');
//                var that = this;
//                clipboard.on('success', function (e) {
//                    // 防止多次点击提示多次
//                    const now = (new Date()).getTime();
//                    if (now - that.lastCopySuccessNotifyTime < 1000) {
//                        return;
//                    }
//                    that.$notify({
//                        title: '成功',
//                        message: '拷贝成功',
//                        type: 'success',
//                        duration: 1000
//                    });
//                    that.lastCopySuccessNotifyTime = now;
//                    e.clearSelection();
//                    return false;
//                });
//            }
            if (clipboard == null) {
                var that = this;
                clipboard = new Clipboard('#copyBtn', {
                    text: function(trigger) {
                        return window.document.getElementById("courseUrlInput").value;
                    }
                });
                clipboard.on('success', function (e) {
                    that.$notify({
                        title: '成功',
                        message: '拷贝成功',
                        type: 'success',
                        duration: 1000
                    });
                    e.clearSelection();
                    return false;
                });
            }
        },
        methods: {
            getCourseCategory(ID) {
                getCategorys(ID).then(response => {
                    const categorys = response.data;
                    for (let i = 0; i < categorys.length; i++) {
                        this.postForm.cateIdList.push(categorys[i].categoryId);
                    }
                }).catch(err => {
                    console.log(err)
                });
            },
            getSourceList() {
                _getSourceList({ page: 1, pageSize: 1000 }).then(response => {
                    this.sourceOptions = response.data.data;
                }).catch(err => {
                    console.log(err)
                });
            },
            getAuthorList() {
                _getAuthorList({ page: 1, pageSize: 1000 }).then(response => {
                    this.authorOptions = response.data.data;
                }).catch(err => {
                    console.log(err)
                });
            },
            getCategoryList() {
                _getCategoryList({ page: 1, pageSize: 1000 }).then(response => {
                    this.categoryOptions = response.data.data;
                }).catch(err => {
                    console.log(err)
                });
            },
            fetchData(ID) {
                getDetail(ID).then(response => {
                    this.postForm.id = response.data.id;
                    this.postForm.name = response.data.name;
                    this.postForm.imgUrl = response.data.imgUrl;
                    this.postForm.briefDesc = response.data.briefDesc;
                    this.postForm.detailDesc = response.data.detailDesc;
                    this.postForm.thumbImgUrl = response.data.thumbImgUrl;
                    this.postForm.authorId = response.data.authorId;
                    this.postForm.sourceId = response.data.sourceId;
                    this.postForm.orgPrice = response.data.orgPrice;
                    this.postForm.discPrice = response.data.discPrice;
                    this.postForm.serial = response.data.serial;
                    this.postForm.buyNote = response.data.buyNote;
                    this.postForm.status = response.data.status;
                    this.courseUrl = process.env.FONT_BASE_API + '/course/' + ID + '?randId=' + response.data.randId;
                }).catch(err => {
                    console.log(err)
                });
            },
            beforeUpload(file) {
                const reg = /(.png|.jpg|.jpeg|.gif|.bmp)$/
                return reg.test(file.name);
            },
            handleSuccess(response) {
                if (response.code === 0) {
                    this.postForm.imgUrl = response.data;
                }
            },
            handleThumbSuccess(response) {
                if (response.code === 0) {
                    this.postForm.thumbImgUrl = response.data;
                }
            },
            onSubmit() {
                console.log('submit!');
                const that = this;
                this.$refs.postForm.validate(valid => {
                    console.log(that.$refs.postForm.validate);
                    console.log('valid=' + valid);
                    if (valid) {
                        this.loading = true;
                        if (that.isUpdate) {
                            update(that.postForm).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '更新成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    this.$router.go(-1);
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        } else {
                            add(that.postForm).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '添加成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    this.$router.go(-1);
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            goBack() {
                this.$router.go(-1);
            },
            copyStringToClipboard() {
                const that = this;
                function handler(event) {
                    event.clipboardData.setData('text/plain', this.courseUrl);
                    that.$notify({
                        title: '成功',
                        message: '拷贝成功',
                        type: 'success',
                        duration: 1000
                    });
                    event.preventDefault();
                    document.removeEventListener('copy', handler, true);
                }
                document.addEventListener('copy', handler, true);
                document.execCommand('copy');
            }
        }
    }
</script>